package org.example.network;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class PageDownload {

    public static void main(String[] args) {
        PageDownload pageDownload = new PageDownload();
        pageDownload.downloadPage("http://www.hyycinfo.com/index.html",
                "E:\\录屏\\154\\0807");
    }

    public void downloadPage(String htmlPath, String dirPath) {
        download(htmlPath, dirPath);
        try {
            Document doc = Jsoup.parse(new URL(htmlPath), 1000);
            // 获取所有的css,js,img元素,下载
            Elements elements = doc.select("link[type=text/css]");
            for (Element element : elements) {
                // http://www.hyycinfo.com/index.html
                //                         css/animate.min.css
                String href = element.attr("href");
                if(href.startsWith("/")){
                    // TODO 绝对路径
                } else {
                    // 相对路径
                    // 截取 http://www.hyycinfo.com/
                    String pathPrefix = htmlPath.substring(0,htmlPath.lastIndexOf("/") + 1);
                    String cssPath = pathPrefix + href;
                    // 构建本地的css文件路径
                    String cssDiskPath = dirPath + File.separator + href;
                    File cssFile = new File(cssDiskPath);
                    // 如果目录不存在, 则创建
                    if(cssFile.getParentFile().exists() == false){
                        cssFile.getParentFile().mkdirs();
                    }
                    download(cssPath, cssFile.getParentFile().getAbsolutePath());
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public void download(String address, String dirPath){
        FileOutputStream fos = null;
        try{
            URL url = new URL(address);
            String webPath = url.getFile();
            String fileName = webPath.substring(webPath.lastIndexOf("/"));
            fos = new FileOutputStream(dirPath + fileName);
            URLConnection urlConnection = url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len = inputStream.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }
            System.out.println("下载完成: " + dirPath + fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
